package com.lsa.letcode.the92.reverseLinkedListII;

import com.lsa.letcode.common.ListNode;

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null) {
        	return null;
        }
        
        ListNode resultHead = head;
        
        ListNode prevHead = null;
        int i;
        for (i = 1; i < m; i++) {
        	if (head == null){
        		throw new IllegalArgumentException();
        	}
        	prevHead = head;
        	head = head.next;
		}
        
        ListNode prev = null;
        ListNode tail = head;
        while(head != null && (i++) <= n) {
        	ListNode next = head.next;
        	head.next = prev;
        	prev = head;
        	head = next;
        }
        
        if (i <= n) {
        	throw new IllegalArgumentException();
        }
        
        if (m == 1){
        	resultHead = prev;
        }
        else {
        	prevHead.next = prev;
        }
        
        tail.next = head; // head = next
        
        return resultHead;
    }
}